package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/streadway/amqp"

	"github.com/labstack/echo"
)

func main() {
	e := echo.New()
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "hello world")
	})
	e.Start("localhost:1324")
	// e.Run(standard.New(":1323"))
}

func init() {
	init_rabbitmq()
}

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
		fmt.Printf("%s: %s", msg, err)
	}
}

func init_rabbitmq() {
	conn, err := amqp.Dial("amqp://rabbitmq:123456@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	// err := ch.Reject()
	exchangeName := "txcommon"
	// 1声明交换路由
	err = ch.ExchangeDeclare(
		exchangeName,
		"fanout",
		true,
		false,
		false,
		false,
		nil,
	)
	failOnError(err, "Failed to declare a exchange")

	q, err := ch.QueueDeclare(
		"",
		false,
		false,
		true,
		false,
		nil,
	)
	failOnError(err, "Failed to declare a queue")

	// 绑定路由声明
	err = ch.QueueBind(
		q.Name,
		"",
		exchangeName,
		true,
		nil,
	)
	failOnError(err, "Failed to bind a queue")

	msgs, err := ch.Consume(
		q.Name,
		"",
		true,
		false,
		false,
		false,
		nil,
	)
	failOnError(err, "Fail to publish a message")
	// err = ch.QueueBind("Agent", "Agent", "Test_01", false, nil)
	// if err != nil {
	// 	log.Println(err)
	// 	return
	// }

	forever := make(chan bool)
	go func() {
		for d := range msgs {
			log.Printf("Received a message: %s", d.Body)
		}
	}()
	log.Printf("Waiting for message.To exit press CTRL+C")
	<-forever
}
